package com.code.question3;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用线程池将一个目录中的所有内容拷贝到另外一个目录中，包含子目录中的内容。
 */
public class Client {
    public static void main(String[] args) {
        String sourceInput="",targetInput="";
        try {
            System.out.println("请输入要复制的文件目录！");
            sourceInput=new BufferedReader(new InputStreamReader(System.in)).readLine();
            File sourceFile = new File(sourceInput);
            if (!sourceFile.exists()){
                System.out.println("复制目录不存在");
                return;
            }
            System.out.println("请输入复制的文件存放目录！");
            targetInput=new BufferedReader(new InputStreamReader(System.in)).readLine();
            if (targetInput.trim()==""){
                System.out.println("文件存放目录不能为空！");
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //开启线程池
        ExecutorService services = Executors.newCachedThreadPool((Runnable r) -> {
            return new Thread(r);
        });
        recursionCopy(services,sourceInput,sourceInput,targetInput);
        services.shutdown();
    }

    /**
     * 递归复制文件夹下所有文件
     *
     * @param sourcePath
     */
    static void recursionCopy(ExecutorService services,String sourcePath, String sourceDir,String targetDir) {
        File sourceFile = new File(sourcePath);
        if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                recursionCopy(services,files[i].getAbsolutePath(),sourceDir,targetDir);
            }
        }else{
            CopyFile cf=new CopyFile();
            cf.setSourceFile(sourceFile);
            File targetFile = new File(sourceFile.getAbsolutePath().replace(sourceDir,targetDir));
            cf.setTargetFile(targetFile);
            services.submit(cf);
        }
    }
}
